import { omit } from 'lodash-es';
import { ApiDataType, appConfig, BaseType, ComponentType, Data, IModalPicker, Modal, newError, PageOut } from '../index';


export interface CondProps {
  component?: ComponentType,
  field: string,
  title: string,
}

export interface ModalPickerProps {
  api: (args: Data) => Promise<PageOut | Data[]> | PageOut | Data[]
  columns: Data[]
  cond?: {
    col: number,
    reset: boolean,
  }
  conds?: CondProps[]
  height?: number | string
  immediate?: boolean
  multiple?: boolean
  rowKey: string
  selectedKeys?: BaseType[]
  showSelected?: boolean
  title: string
  type?: ApiDataType
  width?: number | string
}

export type ModalPickerClassName = keyof IModalPicker

const modalPickerImpl: IModalPicker = {}

export const addModalPicker = (clazz: string, fn: (input: Data, selectedKeys: BaseType[]) => ModalPickerProps): void => {
  modalPickerImpl[clazz] = (input: Data, keys: BaseType[]): Promise<[Data[], BaseType[]]> => {
    const props = fn(input, keys)
    return new Promise((resolve, reject): void => {
      Modal.e.open({
        component: appConfig.modal.modalPicker,
        onClose(isOk: boolean, rows: Data[], keys: BaseType[]) {
          isOk ? resolve([rows, keys]) : reject('没有选择')
        },
        props: {
          ...omit(props, 'title', 'width'),
        },
        title: props.title,
        width: props.width,
      })
    })
  }
}

export async function openModalPicker(clazz: ModalPickerClassName, input: Data = {}, selectedKeys: BaseType[] = []): Promise<[Data[], BaseType[]]> {
  const fn = modalPickerImpl[clazz]
  if (fn) {
    return await fn(input, selectedKeys)
  } else {
    throw newError(`找不到方法: ${clazz}`)
  }
}
